package com.rajeshDyadav.security.messagedigest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD501 {

    public String getMD5(File file) throws NoSuchAlgorithmException, FileNotFoundException {
	MessageDigest digest = MessageDigest.getInstance("MD5");	
	InputStream is = new FileInputStream(file);
	byte[] buffer = new byte[8192];
	int read = 0;
	String output = null;
	try {
	    while ((read = is.read(buffer)) > 0) {
		digest.update(buffer, 0, read);
	    }
	    byte[] md5sum = digest.digest();
	    BigInteger bigInt = new BigInteger(1, md5sum);
	    output = bigInt.toString(16);
	} catch (IOException e) {
	    throw new RuntimeException("Unable to process file for MD5", e);
	} finally {
	    try {
		is.close();
	    } catch (IOException e) {
		throw new RuntimeException("Unable to close input stream for MD5 calculation", e);
	    }
	}
	return output;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, FileNotFoundException {
	MD501 md501 = new MD501();
	//File f = new File("/home/ryadav/Desktop/nirajBuild/RDYExcel2.jar");
	//System.out.println(md501.getMD5(f));
	
	File folder = new File("/home/ryadav/Desktop/nirajBuild");
	File fileList[] = folder.listFiles();
	
	for(int i=0; i<fileList.length; i++) {
	    if (fileList[i].isDirectory()) {
		System.out.println("Directory: " + fileList[i].getPath());		
	    }
	    else if (fileList[i].isFile()) {
		System.out.println("File: " + fileList[i].getPath());		
		System.out.println("MD5: " + md501.getMD5(fileList[i]));
	    }
	}
    }
}